package com.idbk.chargestation.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.View.MeasureSpec;
import android.widget.ImageView;

import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.idbk.chargestation.R;

import java.util.ArrayList;

/**
 * 高德地图点聚合
 */
public class MarkerCluster {

    private Context mContext;

    private MarkerOptions options;
    /**
     * 聚合点内部 包含的实际点
     */
    private ArrayList<LatLng> mPoints;

    private Object mObj;

    private LatLngBounds mBounds;//创建区域

    private static Bitmap mPanel;

    public MarkerCluster(Context context, LatLng latLng, Projection projection) {
        mContext = context;
        mPoints = new ArrayList<LatLng>();
        mPoints.add(latLng);
        //初始化 矩形区域
        Point point = projection.toScreenLocation(latLng);
        int gridSize = 60;
        //西南坐标
        Point southwestPoint = new Point(point.x - gridSize, point.y + gridSize);
        //东北坐标
        Point northeastPoint = new Point(point.x + gridSize, point.y - gridSize);
        //东北角 经纬度
        LatLng ne = projection.fromScreenLocation(northeastPoint);
        //西南角 经纬度
        LatLng sw = projection.fromScreenLocation(southwestPoint);
        //如果东北角纬度小于 西北角纬度，则交换纬度
        if (ne.latitude < sw.latitude) {
            LatLng nee = new LatLng(sw.latitude, ne.longitude);
            LatLng sww = new LatLng(ne.latitude, sw.longitude);
            mBounds = new LatLngBounds(sww, nee);
        } else {
            mBounds = new LatLngBounds(sw, ne);
        }
    }

    /**
     * 是否包含该点
     *
     * @param ll 经纬度
     * @return 是否包含该点
     */
    public boolean containPoint(LatLng ll) {
        return mBounds.contains(ll);
    }

    /**
     * 添加marker
     */
    public void addMarker(LatLng latLng) {
        mPoints.add(latLng);// 添加到列表中
    }

    /**
     * 设置聚合点的中心位置以及图标
     */
    public void finish() {
        mObj = this;
        LatLng latLng;
        int size = mPoints.size();

        if (size == 1) {
            latLng = mPoints.get(0);
        } else {
            double lat = 0;
            double lng = 0;
            for (LatLng op : mPoints) {
                lat += op.latitude;
                lng += op.longitude;
            }
            latLng = new LatLng(lat / size, lng / size);
        }
        options = new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .position(latLng) // 设置中心位置为聚集点的平均位置
                .title("聚合点")
                .icon(getMarkerIcon(mContext, size))
                .draggable(false)
                .zIndex(size)
                .setFlat(true);
    }

    public MarkerOptions getOptions() {
        return options;
    }

    private BitmapDescriptor getMarkerIcon(Context context, int count) {
        Bitmap bmp = getPanelWithNumber(context, count);
        return BitmapDescriptorFactory.fromBitmap(bmp);
    }

    private Bitmap getPanelWithNumber(Context context, int number) {
        Bitmap bmp = getPanel(context);
        Bitmap.Config bitmapConfig = bmp.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }
        //位图资源是不可变的,
        //所以我们需要把它转换成可变
        bmp = bmp.copy(bitmapConfig, true);

        String text = number + "";

        Canvas canvas = new Canvas(bmp);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.rgb(255, 255, 255));
        Resources resources = context.getResources();
        float scale = resources.getDisplayMetrics().density;
        paint.setTextSize((int) (12 * scale));

        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int x = (bmp.getWidth() - bounds.width()) / 2;
        int y = (bmp.getHeight() + bounds.height()) / 2;
        canvas.drawText(text, x, y, paint);

        return bmp;
    }

    private Bitmap getPanel(Context context) {
        if (mPanel == null) {
            ImageView image = new ImageView(context);
            image.setImageResource(R.drawable.ico_map_cluster_digit_2);

            image.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            image.layout(0, 0, image.getMeasuredWidth(), image.getMeasuredHeight());
            image.buildDrawingCache();
            mPanel = image.getDrawingCache();
        }
        return mPanel;
    }

    public Object getUserData() {
        return mObj;
    }

//    public int getInsideCount() {
//        return mPoints.size();
//    }

}